<template>
  <div class="records-page">
    <a-page-header
      title="饮食记录管理"
      sub-title="查看和管理用户饮食记录"
      @back="() => $router.push('/diet')"
    >
    </a-page-header>

    <a-card :bordered="false" style="margin-top: 16px">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item name="keyword" label="用户">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="用户名/手机号"
            allowClear
          />
        </a-form-item>
        
        <a-form-item name="dateRange" label="日期范围">
          <a-range-picker
            v-model:value="searchForm.dateRange"
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
            @change="onDateChange"
          />
        </a-form-item>
        
        <a-form-item name="mealType" label="餐次类型">
          <a-select
            v-model:value="searchForm.mealType"
            style="width: 120px"
            placeholder="全部"
            allowClear
          >
            <a-select-option :value="1">早餐</a-select-option>
            <a-select-option :value="2">午餐</a-select-option>
            <a-select-option :value="3">晚餐</a-select-option>
            <a-select-option :value="4">加餐</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit">
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="records"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        style="margin-top: 16px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'user'">
            <div class="user-info">
              <span class="user-name">用户ID: {{ record.userId }}</span>
            </div>
          </template>
          
          <template v-if="column.key === 'mealType'">
            <a-tag :color="getMealTypeColor(record.mealType)">
              {{ getMealTypeName(record.mealType) }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'foodCount'">
            {{ (record.meals && record.meals.length) || '未知' }}
          </template>
          
          <template v-if="column.key === 'recordTime'">
            {{ formatDateTime(record.recordTime) }}
          </template>
          
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="viewDetail(record)">详情</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条记录吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteRecord(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 饮食记录详情模态框 -->
    <a-modal
      :visible="detailVisible"
      title="饮食记录详情"
      @cancel="detailVisible = false"
      :footer="null"
      width="700px"
    >
      <div v-if="selectedRecord" class="record-detail">
        <div class="record-header">
          <div class="record-user-info">
            <h2>{{ selectedRecord.userNickname || '用户' + selectedRecord.userId }}</h2>
          </div>
          <div class="record-meal-info">
            <a-tag :color="getMealTypeColor(selectedRecord.mealType)" style="margin-right: 8px;">
              {{ getMealTypeName(selectedRecord.mealType) }}
            </a-tag>
            <span>{{ formatDateTime(selectedRecord.mealTime) }}</span>
          </div>
        </div>
        
        <a-divider />
        
        <div class="food-list">
          <h3>食物清单</h3>
          <a-table
            :columns="detailColumns"
            :data-source="selectedRecord.meals || []"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'suitable'">
                <a-tag :color="record.suitable === 1 ? 'green' : 'red'" v-if="record.suitable !== undefined">
                  {{ record.suitable === 1 ? '适合' : '不适合' }}
                </a-tag>
              </template>
            </template>
          </a-table>
          
          <div class="nutrition-summary" v-if="selectedRecord.calories">
            <h3>营养摘要</h3>
            <div class="nutrition-cards">
              <div class="nutrition-card">
                <div class="nutrition-value">{{ selectedRecord.calories || 0 }}</div>
                <div class="nutrition-label">总热量 (kcal)</div>
              </div>
              <div class="nutrition-card">
                <div class="nutrition-value">{{ selectedRecord.carbohydrate || 0 }}</div>
                <div class="nutrition-label">碳水 (g)</div>
              </div>
              <div class="nutrition-card">
                <div class="nutrition-value">{{ selectedRecord.protein || 0 }}</div>
                <div class="nutrition-label">蛋白质 (g)</div>
              </div>
              <div class="nutrition-card">
                <div class="nutrition-value">{{ selectedRecord.fat || 0 }}</div>
                <div class="nutrition-label">脂肪 (g)</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="record-note" v-if="selectedRecord.remark">
          <h3>备注</h3>
          <p>{{ selectedRecord.remark }}</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import dayjs from 'dayjs';

export default defineComponent({
  setup() {
    const loading = ref(false);
    const detailVisible = ref(false);
    const records = ref([]);
    const selectedRecord = ref(null);
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    });
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      dateRange: [],
      mealType: undefined,
      startDate: undefined,
      endDate: undefined
    });
    
    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60
      },
      {
        title: '用户',
        key: 'user',
        width: 150
      },
      {
        title: '餐次',
        dataIndex: 'mealType',
        key: 'mealType',
        width: 80
      },
      {
        title: '食物数量',
        key: 'foodCount',
        width: 90
      },
      {
        title: '总热量(kcal)',
        dataIndex: 'calories',
        key: 'calories',
        width: 120
      },
      {
        title: '记录时间',
        dataIndex: 'mealTime',
        key: 'recordTime',
        width: 150,
        sorter: true
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'note',
        ellipsis: true
      },
      {
        title: '操作',
        key: 'action',
        width: 120,
        fixed: 'right'
      }
    ];
    
    // 详情表格列
    const detailColumns = [
      {
        title: '食物名称',
        dataIndex: 'foodName',
        key: 'foodName'
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity'
      },
      {
        title: '单位',
        dataIndex: 'foodUnit',
        key: 'foodUnit'
      },
      {
        title: '热量(kcal)',
        dataIndex: 'calories',
        key: 'calories'
      },
      {
        title: '碳水(g)',
        dataIndex: 'carbs',
        key: 'carbs'
      },
      {
        title: '适合糖尿病',
        key: 'suitable',
        dataIndex: 'suitable'
      }
    ];
    
    // 日期变化处理
    const onDateChange = (dates) => {
      if (dates && dates.length === 2) {
        searchForm.startDate = dayjs(dates[0]).format('YYYY-MM-DD');
        searchForm.endDate = dayjs(dates[1]).format('YYYY-MM-DD');
      } else {
        searchForm.startDate = undefined;
        searchForm.endDate = undefined;
      }
    };
    
    // 获取餐次类型名称
    const getMealTypeName = (type) => {
      const types = {
        0: '早餐',
        1: '早餐',
        2: '午餐',
        3: '晚餐',
        4: '加餐'
      };
      return types[type] || '未知';
    };
    
    // 获取餐次类型颜色
    const getMealTypeColor = (type) => {
      const colors = {
        0: 'blue',
        1: 'blue',
        2: 'orange',
        3: 'purple',
        4: 'green'
      };
      return colors[type] || 'default';
    };
    
    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '-';
      // 判断是否为时间戳数值
      const timestamp = typeof dateTimeStr === 'number' ? dateTimeStr : parseInt(dateTimeStr);
      if (!isNaN(timestamp)) {
        return dayjs(timestamp).format('YYYY-MM-DD HH:mm');
      }
      return dayjs(dateTimeStr).format('YYYY-MM-DD HH:mm');
    };
    
    // 获取饮食记录列表
    const fetchRecords = async () => {
      try {
        loading.value = true;
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          ...searchForm
        };
        
        // 添加日期范围参数
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.startDate = dayjs(searchForm.dateRange[0]).format('YYYY-MM-DD');
          params.endDate = dayjs(searchForm.dateRange[1]).format('YYYY-MM-DD');
        }
        
        // 移除undefined或null的属性
        Object.keys(params).forEach(key => {
          if (params[key] === undefined || params[key] === null) {
            delete params[key];
          }
        });
        
        const response = await axios.get('/admin/diet/records', { params });
        if (response.data.code === 0) {
          const data = response.data.data;
          records.value = data.list || [];
          pagination.total = data.total || 0;
        } else {
          message.error(response.data.msg || '获取饮食记录失败');
        }
      } catch (error) {
        console.error('获取饮食记录失败', error);
        message.error('获取饮食记录失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 表格变化处理(分页、排序等)
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchRecords();
    };
    
    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      fetchRecords();
    };
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = '';
      searchForm.dateRange = [];
      searchForm.mealType = undefined;
      searchForm.startDate = undefined;
      searchForm.endDate = undefined;
      pagination.current = 1;
      fetchRecords();
    };
    
    // 查看详情
    const viewDetail = async (record) => {
      try {
        loading.value = true;
        const response = await axios.get(`/admin/diet/records/${record.id}`);
        
        if (response.data.code === 0) {
          selectedRecord.value = response.data.data;
          detailVisible.value = true;
        } else {
          message.error(response.data.msg || '获取饮食记录详情失败');
        }
      } catch (error) {
        console.error('获取饮食记录详情失败', error);
        message.error('获取饮食记录详情失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 删除记录
    const deleteRecord = async (id) => {
      try {
        loading.value = true;
        const response = await axios.delete(`/admin/diet/records/${id}`);
        if (response.data.code === 0) {
          message.success('删除成功');
          fetchRecords();
        } else {
          message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败');
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchRecords();
    });
    
    return {
      loading,
      detailVisible,
      records,
      selectedRecord,
      pagination,
      searchForm,
      columns,
      detailColumns,
      onDateChange,
      getMealTypeName,
      getMealTypeColor,
      formatDateTime,
      handleTableChange,
      handleSearch,
      resetSearch,
      viewDetail,
      deleteRecord
    };
  }
});
</script>

<style scoped>
.records-page {
  margin: 0 16px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
}

.user-phone {
  font-size: 12px;
  color: #999;
}

.record-detail {
  padding: 0 16px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.record-user-info h2 {
  margin: 0 0 8px 0;
}

.record-user-info p {
  margin: 0;
  color: #666;
}

.record-meal-info {
  text-align: right;
}

.food-list {
  margin-bottom: 24px;
}

.nutrition-summary {
  margin-top: 24px;
}

.nutrition-cards {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
}

.nutrition-card {
  width: 23%;
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 12px;
  text-align: center;
}

.nutrition-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.nutrition-label {
  color: #666;
  font-size: 12px;
}

.record-note {
  margin-top: 24px;
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 12px;
}
</style> 